package ui;

import dao.DataChangeListener;
import dao.DataManager;
import java.awt.*;
import java.util.List;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import model.ClassRoom;
import model.Student;

public class StudentManagementPanel extends JPanel implements DataChangeListener {
    private JTable studentTable;
    private DefaultTableModel tableModel;
    private JComboBox<ClassRoom> classComboBox;
    
    public StudentManagementPanel() {
        setLayout(new BorderLayout());
        initComponents();
        DataManager.getInstance().addDataChangeListener(this);
    }
    
    private void initComponents() {
        // 创建顶部选择面板
        JPanel topPanel = new JPanel();
        classComboBox = new JComboBox<>();
        
        topPanel.add(new JLabel("选择班级："));
        topPanel.add(classComboBox);
        
        // 创建表格
        String[] columnNames = {"ID", "姓名", "性别", "考勤", "答题分数"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        studentTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(studentTable);
        
        // 创建按钮
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("新增学生");
        JButton editButton = new JButton("编辑学生");
        JButton deleteButton = new JButton("删除学生");
        
        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        
        // 添加到面板
        add(topPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
        
        // 添加事件监听
        classComboBox.addActionListener(e -> refreshStudentTable());
        
        addButton.addActionListener(e -> showAddDialog());
        editButton.addActionListener(e -> showEditDialog());
        deleteButton.addActionListener(e -> deleteStudent());
        
        // 更新下拉框
        updateClassComboBox();
    }
    
    @Override
    public void onDataChanged() {
        updateClassComboBox();
        refreshStudentTable();
    }
    
    private void updateClassComboBox() {
        ClassRoom selectedClass = (ClassRoom) classComboBox.getSelectedItem();
        
        classComboBox.removeAllItems();
        List<ClassRoom> classes = DataManager.getInstance().getAllClasses();
        for (ClassRoom classroom : classes) {
            classComboBox.addItem(classroom);
        }
        
        if (selectedClass != null) {
            for (int i = 0; i < classComboBox.getItemCount(); i++) {
                ClassRoom item = classComboBox.getItemAt(i);
                if (item.getId() == selectedClass.getId()) {
                    classComboBox.setSelectedIndex(i);
                    break;
                }
            }
        } else if (classComboBox.getItemCount() > 0) {
            classComboBox.setSelectedIndex(0);
        }
    }
    
    private void refreshStudentTable() {
        tableModel.setRowCount(0);
        if (classComboBox.getSelectedItem() == null) return;
        
        ClassRoom selectedClass = (ClassRoom) classComboBox.getSelectedItem();
        List<Student> students = DataManager.getInstance().getStudentsByClass(selectedClass.getId());
        
        for (Student student : students) {
            tableModel.addRow(new Object[]{
                student.getId(),
                student.getName(),
                student.getGender(),
                student.getAttendance(),
                student.getQuestionScore()
            });
        }
    }
    
    private void showAddDialog() {
        if (classComboBox.getSelectedItem() == null) {
            JOptionPane.showMessageDialog(this, "请先选择班级！");
            return;
        }
        
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), "新增学生", true);
        dialog.setLayout(new GridLayout(5, 2, 5, 5));
        
        JTextField nameField = new JTextField();
        JComboBox<String> genderComboBox = new JComboBox<>(new String[]{"男", "女"});
        
        dialog.add(new JLabel("姓名:"));
        dialog.add(nameField);
        dialog.add(new JLabel("性别:"));
        dialog.add(genderComboBox);
        
        JButton confirmButton = new JButton("确定");
        confirmButton.addActionListener(e -> {
            if (nameField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "学生姓名不能为空！");
                return;
            }
            
            ClassRoom selectedClass = (ClassRoom) classComboBox.getSelectedItem();
            
            int newId = DataManager.getInstance().getStudentsByClass(selectedClass.getId()).size() + 1;
            Student newStudent = new Student(newId, nameField.getText(), 
                (String)genderComboBox.getSelectedItem(), selectedClass.getId());
            
            DataManager.getInstance().addStudent(newStudent);
            refreshStudentTable();
            dialog.dispose();
        });
        
        dialog.add(confirmButton);
        dialog.add(new JButton("取消") {{ addActionListener(e -> dialog.dispose()); }});
        
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    private void showEditDialog() {
        int selectedRow = studentTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要编辑的学生！");
            return;
        }
        
        // 获取选中行的数据
        int id = (int) tableModel.getValueAt(selectedRow, 0);
        String currentName = (String) tableModel.getValueAt(selectedRow, 1);
        String currentGender = (String) tableModel.getValueAt(selectedRow, 2);
        int currentAttendance = (int) tableModel.getValueAt(selectedRow, 3);
        int currentScore = (int) tableModel.getValueAt(selectedRow, 4);
        
        // 创建编辑对话框
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), "编辑学生", true);
        dialog.setLayout(new GridLayout(6, 2, 5, 5));
        
        // 创建输入组件
        JTextField nameField = new JTextField(currentName);
        JComboBox<String> genderComboBox = new JComboBox<>(new String[]{"男", "女"});
        genderComboBox.setSelectedItem(currentGender);
        
        // 创建考勤和得分的输入组件
        JSpinner attendanceSpinner = new JSpinner(new SpinnerNumberModel(currentAttendance, 0, 100, 1));
        JSpinner scoreSpinner = new JSpinner(new SpinnerNumberModel(currentScore, 0, 100, 1));
        
        // 添加组件到对话框
        dialog.add(new JLabel("姓名:"));
        dialog.add(nameField);
        dialog.add(new JLabel("性别:"));
        dialog.add(genderComboBox);
        dialog.add(new JLabel("考勤次数:"));
        dialog.add(attendanceSpinner);
        dialog.add(new JLabel("答题得分:"));
        dialog.add(scoreSpinner);
        
        // 确定按钮
        JButton confirmButton = new JButton("确定");
        confirmButton.addActionListener(e -> {
            if (nameField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "学生姓名不能为空！");
                return;
            }
            
            // 获取当前班级
            ClassRoom selectedClass = (ClassRoom) classComboBox.getSelectedItem();
            
            // 创建更新后的学生对象
            Student updatedStudent = new Student(id, nameField.getText(), 
                (String)genderComboBox.getSelectedItem(), selectedClass.getId());
            updatedStudent.setAttendance((int)attendanceSpinner.getValue());
            updatedStudent.setQuestionScore((int)scoreSpinner.getValue());
            
            // 保持原有的小组ID
            Student oldStudent = DataManager.getInstance().getStudentsByClass(selectedClass.getId())
                .stream()
                .filter(s -> s.getId() == id)
                .findFirst()
                .orElse(null);
                
            if (oldStudent != null) {
                updatedStudent.setGroupId(oldStudent.getGroupId());
            }
            
            // 更新数据
            DataManager.getInstance().updateStudent(updatedStudent);
            
            // 刷新表格
            refreshStudentTable();
            dialog.dispose();
        });
        
        // 取消按钮
        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(e -> dialog.dispose());
        
        dialog.add(confirmButton);
        dialog.add(cancelButton);
        
        // 显示对话框
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    private void deleteStudent() {
        int selectedRow = studentTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的学生！");
            return;
        }
        
        int id = (int) tableModel.getValueAt(selectedRow, 0);
        int confirm = JOptionPane.showConfirmDialog(this, 
            "确定要删除这个学生吗？", "确认删除", 
            JOptionPane.YES_NO_OPTION);
            
        if (confirm == JOptionPane.YES_OPTION) {
            DataManager.getInstance().removeStudent(id);
            refreshStudentTable();
        }
    }
} 